import React, { Component } from "react";
import {
  Input,
  Select,
  Button,
  Modal,
  message,
  TreeSelect,
  Spin,
  Form
} from "antd";
import { connect } from "dva";
import setData from "./data";
import ConfigPage from "./components/ConfigPage";
import styles from "./AddSituationPage.less";
import SelectModal from "../add/components/SelectModal";
import setvalues from "./setvalues";

const { Option } = Select;
const { TextArea } = Input;

@connect(stores => ({
  coldata: stores.user,
  sceneData: stores.addScene,
  dataSourceData: stores.dataSource,
  orgList: stores.adddataSource,
  personDep: stores.personSelectModel
}))
@Form.create()
class AddSituationPage extends Component {
  state = setvalues.stateData;

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: "dataSource/getDatasourceList",
      payload: { useStatus: 1, pageNum: "1", pageSize: "10000" }
    });
    dispatch({
      type: "adddataSource/getOrgList",
      payload: {}
    });
    this.setValue();
  }

  setValue = () => {
    this.setState({ loadingEdit: true });
    setTimeout(() => {
      const { key } = this.props.sceneData;
      const {
        coldata: {
          userInfo: {
            userCode = "",
            userId = "",
            userName = "",
            department = "",
            departmentName = ""
          }
        } = {},
        dispatch
      } = this.props;
      if (key.operate === "add") {
        dispatch({
          type: "personSelectModel/queryByName",
          payload: userCode
        }).then(() => {
          this.setState({
            manager: [userId],
            managerName: [userName],
            depart: department,
            departmentName
          });
        });
      }
      if (key.operate === "mod") {
        this.setState({ sceneTemplateId: key.sceneTemplateId });
        dispatch({
          type: "addScene/detailScene",
          payload: { sceneTemplateId: key.sceneTemplateId }
        }).then(() => {
          const { detailScene = {} } = this.props.sceneData;
          let location = {};
          let Similarity = {};
          dispatch({
            type: "addScene/getParams",
            payload: {
              dsId: detailScene.dsId
            }
          });
          const { sceneTemplateRules = [], ifUse } = detailScene;
          if (sceneTemplateRules !== null) {
            sceneTemplateRules.forEach(item => {
              if (
                item.messageType === 1 &&
                (item.messageUnitName === "position" ||
                  item.messageUnitName === "similarity")
              ) {
                if (item.messageUnitName === "position") {
                  location = {
                    messageUnitName: "position",
                    messageType: 1,
                    messageParameter: item.messageParameter,
                    parameterNullContent: item.parameterNullContent
                  };
                }
                if (item.messageUnitName === "similarity") {
                  Similarity = {
                    messageUnitName: "similarity",
                    messageType: 1,
                    messageParameter: item.messageParameter,
                    parameterNullContent: item.parameterNullContent
                  };
                }
              }
            });
          }
          const { dataInput, ContentEdit, i, urlPic } = setvalues.setValues(
            detailScene
          );
          let FeedbackV;
          if (detailScene.commentType) {
            if (detailScene.commentType !== "1" && detailScene.commentType !== "2") {
              FeedbackV = "3";
            } else {
              FeedbackV = detailScene.commentType;
            }
          }
          this.setState({
            scene: detailScene.templateName,
            depart: detailScene.ownerDept,
            departmentName: detailScene.ownerDeptName,
            source: detailScene.dsId ? detailScene.dsId : "",
            description: detailScene.templateDescription,
            Content: detailScene.contentType ? detailScene.contentType : 1,
            // Feedback: detailScene.commentType,
            Feedback: FeedbackV,
            dataInput,
            ContentEdit,
            num: i,
            urlPic,
            picNum: urlPic.length,
            noContent:
              detailScene.sceneTemplateRules &&
              detailScene.sceneTemplateRules.length > 0
                ? detailScene.sceneTemplateRules[0].parameterNullContent
                : "",
            ContentShow: this.contentShowGet(detailScene),
            location,
            Similarity,
            editable: ifUse === 0,
            manager: [
              detailScene.owners && detailScene.owners.length > 0
                ? detailScene.owners[0].key
                : ""
            ],
            managerName: [
              detailScene.owners && detailScene.owners.length > 0
                ? detailScene.owners[0].name
                : ""
            ]
          });
        });
      }
      this.setState({ loadingEdit: false });
    }, 500);
  };

  contentShowGet = values => {
    if (values.commentType === "1") {
      const tmp = [];
      values.msgCommentSceneQueryList.forEach(item => {
        tmp.push({
          value: item.content,
          sceneTemplateId: item.sceneTemplateId,
          commentTemplateId: item.commentTemplateId
        });
      });
      return tmp;
    }
    return [];
  };

  getContent = e => {
    if (e && e !== "") {
      this.setState({
        conVisible: false
      });
    }
    this.setState({
      Content: e
    });
  };

  getFeedback = e => {
    if (e && e !== "") {
      this.setState({
        feedVisible: false
      });
    }
    this.setState({
      Feedback: e
    });
  };

  getEdit = (e, dataInput, num) => {
    if (e && e !== "") {
      this.setState({
        editVisible: false
      });
    }
    this.setState({
      ContentEdit: e,
      num,
      dataInput
    });
  };

  getShow = e => {
    if (e) {
      e.forEach(item => {
        if (item.value !== "") {
          this.setState({
            showVisible: false
          });
        }
      });
    }
    this.setState({
      ContentShow: e
    });
  };

  getNoCon = e => {
    this.setState({
      noContent: e.target.value
    });
  };

  getDel = deleteData => {
    this.setState({ deleteData });
  };

  sceneGet = e => {
    if (e.target.value !== "") {
      this.setState({
        sceneNameVisible: false
      });
    }
    this.setState({
      scene: e.target.value
    });
  };

  departGet = (e, departmentName) => {
    if (e && e !== "") {
      this.setState({
        depVisible: false
      });
    }
    this.setState({
      depart: !e ? "" : e,
      departmentName: departmentName[0]
    });
  };

  sourceGet = e => {
    const { dispatch } = this.props;
    const { Content, location, Similarity } = this.state;
    dispatch({
      type: "addScene/getParams",
      payload: {
        dsId: e * 1
      }
    });
    if (e && e !== "") {
      this.setState({
        sourceVisible: false
      });
    }
    this.setState({
      urlPic:
        Content === "4"
          ? [
              { key: 0, value: "" },
              { key: 1, value: "" },
              { key: 2, value: "" }
            ]
          : [{ key: 0, value: "" }],
      picNum: Content === "4" ? 3 : 1,
      location:
        Content === "4"
          ? {
              messageUnitName: "position",
              messageType: 1,
              messageParameter: ""
            }
          : location,
      Similarity:
        Content === "4"
          ? {
              messageUnitName: "similarity",
              messageType: 1,
              messageParameter: ""
            }
          : Similarity,
      num: 0,
      // ContentEdit: "",
      // dataInput: [],
      source: e
    });
  };

  desGet = e => {
    this.setState({
      description: e.target.value,
      descripVisible: false
    });
  };

  urlGet = e => {
    this.setState({
      urlPic: e,
      picVisible: false
    });
  };

  // 获取复选框选择
  checkValueGet = e => {
    this.setState({
      checkValue: e,
      feedTextVisible: false
    });
  };

  // 获取文本反馈配置文本
  feedTextGet = e => {
    this.setState({
      feedTextValue: e,
      feedTextVisible: false
    });
  };

  save = () => {
    const {
      scene,
      depart,
      source,
      description,
      Content,
      Feedback,
      ContentEdit,
      ContentShow,
      noContent,
      urlPic,
      manager,
      managerName,
      sceneTemplateId,
      dataInput,
      checkValue
    } = this.state;
    const { key } = this.props.sceneData;
    const { dispatch } = this.props;
    let a = true;
    if (scene === "") {
      this.setState({ sceneNameVisible: true });
      a = false;
    }
    if (scene.split("").length > 20 || noContent.split("").length > 25) {
      a = false;
    }
    if (depart === "") {
      this.setState({ depVisible: true });
      a = false;
    }
    if (source === "") {
      this.setState({ sourceVisible: true });
      a = false;
    }
    if (Content === "") {
      this.setState({ conVisible: true });
      a = false;
    }
    if (Feedback === "") {
      this.setState({ feedVisible: true });
      a = false;
    }
    if (Content !== "3" && ContentEdit === "") {
      this.setState({ editVisible: true });
      a = false;
    }
    if (description === "") {
      this.setState({ descripVisible: true });
      a = false;
    }
    if (ContentShow && Feedback === "1") {
      let tmp = 0;
      ContentShow.forEach(item => {
        if (item.value !== "") {
          tmp += 1;
        }
      });
      if (tmp < 2) {
        this.setState({ showVisible: true });
        a = false;
      }
    }
    if (Content !== "1") {
      if (urlPic.length === 0) {
        this.setState({
          picVisible: true
        });
        a = false;
      }
      urlPic.forEach(item => {
        if (item.value === "") {
          this.setState({
            picVisible: true
          });
          a = false;
        }
      });
      if (Content === "4") {
        if (
          this.state.Similarity.messageParameter === "" ||
          this.state.location.messageParameter === ""
        ) {
          this.setState({
            picVisible: true
          });
          a = false;
        }
      }
    }
    if (!a) {
      return false;
    }
    const msgCommentTemplates = [];
    if (key.operate === "add") {
      ContentShow.forEach(item => {
        if (item.value !== "") {
          msgCommentTemplates.push({ content: item.value });
        }
      });
    } else {
      ContentShow.forEach(item => {
        if (item.value !== "" && item.add) {
          msgCommentTemplates.push({
            content: item.value,
            sceneTemplateId: this.state.sceneTemplateId
          });
        }
        if (item.value !== "" && !item.add) {
          msgCommentTemplates.push({
            content: item.value,
            sceneTemplateId: item.sceneTemplateId,
            commentTemplateId: item.commentTemplateId
          });
        }
        if (item.value === "" && !item.add) {
          msgCommentTemplates.push({
            content: item.value,
            sceneTemplateId: item.sceneTemplateId,
            stateDelete: 1,
            commentTemplateId: item.commentTemplateId
          });
        }
      });
    }
    const temp =
      key.operate === "add"
        ? {
            templateName: scene,
            dsId: source,
            ownerDept: depart,
            ownerDeptName: this.state.departmentName,
            templateDescription: description,
            owners: [{ key: manager[0], name: managerName[0] }]
          }
        : {
            sceneTemplateId,
            templateName: scene,
            dsId: source,
            ownerDept: depart,
            ownerDeptName: this.state.departmentName,
            templateDescription: description,
            owners: [{ key: manager[0], name: managerName[0] }]
          };
    const { textArr, TextPic, PicArr } = setData.setData(
      key,
      dataInput,
      urlPic,
      this.state.location,
      this.state.Similarity,
      this.state.Content,
      noContent
    );
    if (Content === "1" && Feedback === "1") {
      dispatch({
        type: key.operate === "add" ? "addScene/AddScene" : "addScene/ModScene",
        payload: {
          ...temp,
          sceneTemplateRules: textArr,
          commentType: Feedback,
          msgCommentTemplates,
          contentType: Content
        }
      }).then(() => {
        this.addOrMod();
      });
    }
    if (Content === "1" && Feedback === "2") {
      dispatch({
        type: key.operate === "add" ? "addScene/AddScene" : "addScene/ModScene",
        payload: {
          ...temp,
          sceneTemplateRules: textArr,
          commentType: Feedback,
          contentType: Content
        }
      }).then(() => {
        this.addOrMod();
      });
    }

    if (Content === "1" && Feedback === "3") {
      dispatch({
        type: key.operate === "add" ? "addScene/AddScene" : "addScene/ModScene",
        payload: {
          ...temp,
          sceneTemplateRules: textArr,
          commentType: checkValue,
          contentType: Content,
          msgCommentTemplates
        }
      }).then(() => {
        this.addOrMod();
      });
    }
    if (Content === "3" && Feedback === "1") {
      dispatch({
        type: key.operate === "add" ? "addScene/AddScene" : "addScene/ModScene",
        payload: {
          ...temp,
          sceneTemplateRules: PicArr,
          commentType: Feedback,
          msgCommentTemplates,
          contentType: Content
        }
      }).then(() => {
        this.addOrMod();
      });
    }
    if (Content === "3" && Feedback === "2") {
      dispatch({
        type: key.operate === "add" ? "addScene/AddScene" : "addScene/ModScene",
        payload: {
          ...temp,
          sceneTemplateRules: PicArr,
          commentType: Feedback,
          contentType: Content
        }
      }).then(() => {
        this.addOrMod();
      });
    }
    if (Content === "3" && Feedback === "3") {
      dispatch({
        type: key.operate === "add" ? "addScene/AddScene" : "addScene/ModScene",
        payload: {
          ...temp,
          sceneTemplateRules: PicArr,
          commentType: checkValue,
          contentType: Content
        }
      }).then(() => {
        this.addOrMod();
      });
    }

    if ((Content === "2" || Content === "4") && Feedback === "1") {
      dispatch({
        type: key.operate === "add" ? "addScene/AddScene" : "addScene/ModScene",
        payload: {
          ...temp,
          sceneTemplateRules: TextPic,
          msgCommentTemplates,
          commentType: Feedback,
          contentType: Content
        }
      }).then(() => {
        this.addOrMod();
      });
    }
    if ((Content === "2" || Content === "4") && Feedback === "2") {
      dispatch({
        type: key.operate === "add" ? "addScene/AddScene" : "addScene/ModScene",
        payload: {
          ...temp,
          sceneTemplateRules: TextPic,
          commentType: Feedback,
          contentType: Content
        }
      }).then(() => {
        this.addOrMod();
      });
    }
    if ((Content === "2" || Content === "4") && Feedback === "3") {
      dispatch({
        type: key.operate === "add" ? "addScene/AddScene" : "addScene/ModScene",
        payload: {
          ...temp,
          sceneTemplateRules: TextPic,
          commentType: checkValue,
          contentType: Content
        }
      }).then(() => {
        this.addOrMod();
      });
    }
    return true;
  };

  urlDel = deleteUrl => {
    this.setState({ deleteUrl });
  };

  addOrMod = () => {
    const { history } = this.props;
    const { addErrCode, modErrCode, key, errMsg } = this.props.sceneData;
    if (addErrCode === 0 && key.operate === "add") {
      message.success("保存成功");
      history.push("/intellPush/recommendCenter/situation");
    }
    if (addErrCode !== 0 && key.operate === "add") {
      message.error("保存失败，".concat(errMsg));
    }
    if (modErrCode === 0 && key.operate === "mod") {
      message.success("修改成功");
      history.push("/intellPush/recommendCenter/situation");
    }
    if (modErrCode !== 0 && key.operate === "mod") {
      message.error("修改失败，".concat(errMsg));
    }
  };

  onCancel = () => {
    const { history } = this.props;
    Modal.confirm({
      title: "是否直接关闭此场景？",
      onOk() {
        history.push("/intellPush/recommendCenter/situation");
      },
      onCancel() {}
    });
  };

  selSimilarity = e => {
    const { Similarity } = this.state;
    Similarity.messageParameter = e;
    this.setState({
      Similarity
    });
  };

  confirm = (e, desc) => {
    this.setState({ selectVisible: false, managerName: desc, manager: e });
  };

  closeModal = () => {
    this.setState({ selectVisible: false });
  };

  selLocation = e => {
    const { location } = this.state;
    location.messageParameter = e;
    this.setState({
      location
    });
  };

  render() {
    const { coldata, sceneData } = this.props;
    const { collapsed } = coldata;
    const { manager, managerName, selectVisible, editable } = this.state;
    const { loading = false, paramList = [] } = sceneData;
    const { dataSourceData } = this.props;
    const { dsList = [] } = dataSourceData;
    const { orgList } = this.props;
    const { orgTree = [] } = orgList;
    const { getFieldDecorator } = this.props.form;
    
    return (
      <div>
        <div className={styles.root}>
          <SelectModal
            select={manager}
            selectdesc={managerName}
            visible={selectVisible}
            closeModal={this.closeModal}
            confirm={this.confirm}
            isMutiple={false}
            manager={true}
          />
          <Spin spinning={this.state.loadingEdit || loading}>
            <div className={styles.top}>
              <div className={styles.title}>基本信息</div>
              <div className={styles.basic}>
                <div className={styles.choice1}>
                  <div style={{ display: "flex", marginTop: 5 }}>
                    <span className={styles.star}>*</span>场景名称：
                  </div>
                  <Form>
                    <Form.Item>
                      {getFieldDecorator("scene", {
                        rules: [{ max: 20, message: "场景名称少于20个字" }],
                        initialValue: this.state.scene
                      })(
                        <Input
                          className={
                            this.state.sceneNameVisible
                              ? styles.input
                              : styles.notEmpty
                          }
                          placeholder="请输入场景名称"
                          onChange={this.sceneGet}
                          value={this.state.scene}
                        />
                      )}
                    </Form.Item>
                  </Form>
                </div>
                {this.state.sceneNameVisible ? (
                  <span className={styles.hint}>场景名称不能为空</span>
                ) : null}
                <div className={styles.choice2}>
                  <span className={styles.star}>*</span>数据源：
                  <Select
                    showSearch
                    className={
                      this.state.sourceVisible ? styles.sel : styles.notEmpty
                    }
                    placeholder="请输入数据源"
                    onSelect={this.sourceGet}
                    value={String(this.state.source)}
                    disabled={!editable}
                    filterOption={(input, option) =>
                      option.props.children
                        .toLowerCase()
                        .indexOf(input.toLowerCase()) >= 0
                    }
                  >
                    {dsList.map(item => (
                      <Option value={String(item.dsId)} key={item.dsId}>
                        {item.dsName}
                      </Option>
                    ))}
                  </Select>
                </div>
                {this.state.sourceVisible ? (
                  <span className={styles.hint}>数据源不能为空</span>
                ) : null}
                <div className={styles.choice4}>
                  <span className={styles.star}>*</span>归属部门：
                  <TreeSelect
                    treeData={orgTree}
                    className={
                      this.props.depVisible ? styles.tree : styles.notEmpty
                    }
                    dropdownStyle={{ maxHeight: 350, overflow: "auto" }}
                    // allowClear
                    onChange={this.departGet}
                    value={String(this.state.depart)}
                    disabled={!editable}
                    // treeCheckable
                    showCheckedStrategy="SHOW_PARENT"
                  />
                </div>
                {this.state.depVisible ? (
                  <span className={styles.hint}>部门不能为空</span>
                ) : null}
                <div className={styles.choice2}>
                  <span className={styles.star}>*</span>管理员：
                  <Input
                    style={{ width: 466 }}
                    placeholder="请选择管理员"
                    value={
                      managerName && managerName.length > 0
                        ? managerName[0]
                        : ""
                    }
                    disabled={!editable}
                    onClick={() => {
                      this.setState({ selectVisible: true });
                    }}
                  />
                </div>
                <div className={styles.choice5}>
                  <span className={styles.star}>*</span>场景概述：
                  <TextArea
                    style={{
                      width: 466,
                      height: 120,
                      border: this.state.descripVisible
                        ? "1px solid #e23c39"
                        : ""
                    }}
                    placeholder="请输入场景概述，100字以内"
                    onChange={this.desGet}
                    value={this.state.description}
                    maxLength={100}
                  />
                </div>
                {this.state.descripVisible ? (
                  <span className={styles.hint} style={{ marginTop: 4 }}>
                    场景概述不能为空
                  </span>
                ) : null}
              </div>
            </div>
          </Spin>
          <Spin spinning={this.state.loadingEdit || loading}>
            <div className={styles.bottom}>
              <ConfigPage
                source={String(this.state.source)}
                getContent={this.getContent}
                getEdit={this.getEdit}
                getFeedback={this.getFeedback}
                getNoCon={this.getNoCon}
                getShow={this.getShow}
                urlGet={this.urlGet}
                checkValue={this.checkValueGet}
                feedText={this.feedTextGet}
                conVisible={this.state.conVisible}
                editVisible={this.state.editVisible}
                feedVisible={this.state.feedVisible}
                showVisible={this.state.showVisible}
                ContentType={this.state.Content}
                FeedbackType={this.state.Feedback}
                urlPic={this.state.urlPic}
                ContentEdit={this.state.ContentEdit}
                ContentEditArr={this.state.ContentEditArr}
                noContent={this.state.noContent}
                key={this.props.sceneData}
                sceneTemplateId={this.state.sceneTemplateId}
                picVisible={this.state.picVisible}
                getDel={this.getDel}
                urlDel={this.urlDel}
                selSimilarity={this.selSimilarity}
                selLocation={this.selLocation}
                Similarity={this.state.Similarity.messageParameter}
                location={this.state.location.messageParameter}
                paramList={paramList}
                editable={editable}
                dataInput={this.state.dataInput}
                num={this.state.num}
              />
            </div>
          </Spin>
        </div>
        <div
          style={{
            position: "fixed",
            backgroundColor: "#fff",
            bottom: 0,
            // marginRight: 24,
            marginLeft: -16,
            width: collapsed ? "calc(100% - 66px)" : "calc(100% - 202px)",
            display: "flex",
            justifyContent: "flex-end",
            height: 64,
            alignItems: "center",
            boxShadow: "0px -1px 2px 0px rgba(0, 0, 0, 0.03)",
            borderTop: "1px solid #e8e8e8"
          }}
        >
          <Button onClick={this.onCancel}>取消</Button>
          <Button
            type="primary"
            style={{ marginLeft: 8, marginRight: 16 }}
            onClick={this.save}
          >
            提交
          </Button>
        </div>
      </div>
    );
  }
}

export default AddSituationPage;
